package com.feib.soeasy.security;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.feib.soeasy.model.User;
import com.feib.soeasy.service.UserService;

/**
 * @title (#)SoeasyUserDetailService.java<br>
 * @description <br>
 * @author Anson Tsai<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/30 create by Anson Tsai<br>
 */
@Service("SoeasyUserDetailService")
public class SoeasyUserDetailService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(SoeasyUserDetailService.class);

    @Autowired
    private UserService userService;

    /*
     * (non-Javdoc)
     * 
     * @see org.springframework.security.core.userdetails.UserDetailsService#
     * loadUserByUsername(java.lang.String)
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyUserDetailService.loadUserByUsername(String) - start");
        }
        if (StringUtils.isBlank(userName)) {
            String message = "UserName為空值!!";
            logger.trace(message);
            throw new UsernameNotFoundException(message);
        }

        String[] userNameTemp = userName.split("_conjunction_");
        if (2 != userNameTemp.length){
            String message = "UserName錯誤!!";
            logger.trace(message);
            throw new UsernameNotFoundException(message);
        }
        String groupNo = userNameTemp[0];// 帳單業者統一編號
        String userId = userNameTemp[1];// 使用者名稱
        logger.trace("groupNo : " + groupNo);
        logger.trace("userId : " + userId);
        // 取得用戶的密碼
        User user = userService.loginByUerIdGroupNo(userId, groupNo);

        if (null == user) {
            String message = "業者代號  : " + groupNo + "，使用者名稱 : " + userId + "不存在!!";
            logger.trace(message);
            
            message = "使用者認證資訊有誤！請重新輸入，謝謝。";
            throw new UsernameNotFoundException(message);
        }

        SoeasyUserDetails userWrapper = new SoeasyUserDetails(user);

//        Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
//
//        String passWord = null;
//        
//        passWord = user.getUserPassWord();
//
//        // 獲得用戶的角色
//        Set<Role> roles = user.getRoles();
//        for (Role r : roles) {
//            GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl(r.getRolePk()+ "_" + r.getRoleName());
//            if (logger.isDebugEnabled()) {
//                logger.debug("用戶：[" + user.getUserName() + "]， 擁有角色：[" + r.getRolePk()+ "_" + r.getRoleName() + "]");
//            }
//            auths.add(grantedAuthorityImpl);
//        }
//
//        org.springframework.security.core.userdetails.User userWrapper = new org.springframework.security.core.userdetails.User(userName, passWord, user.getEnabled(), true, !new Date().after(user.getPwdExpiredDate()), !user.getLocked(), auths);

        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyUserDetailService.loadUserByUsername(String) - end");
        }

        return userWrapper;
    }

}
